package seedswapapplication
/*
 * SeedStorageController handles all access to the database with regards to Seeds
 */
class SeedStorageController {
	/*
	 * This action takes search parameters and generates a list of seeds for display
	 * based on those search parameters. It then directs to a page that can display
	 * the search results. Invalid searches and failed searches are handled here
	 */
	def searchResults =
	{
		if(!params.hardinessZone && !params.scientificName)
		{
			flash.message = "Please select Hardiness Zone or Scientific Name to search by."
			redirect(controller:'client',action:'searchSeedPage')
		}
		else
		{
			def seedList
			if(params.hardinessZone)
				seedList = Seed.findAllByHardiness(params.query)
			else
				seedList = Seed.findAllByScientificName(params.query)
			if(seedList)
				[seedList:seedList,query:params.query]
			else
			{
				flash.message = "We're sorry. Your search for \""+params.query+"\" did not return any results. Please try another search"
				redirect(controller:'client', action: 'searchSeedPage')
			}
		}
	}
	/*
	 * This action searches the database to find all seeds owned by the current user
	 * and directs to a page to display this list
	 */
	def viewSeeds =
	{
		if(session.username)
		{
			def seedList = Seed.findAllByFarmerName(session.username)
			[seedList:seedList,username:session.username]
		}
		else
		{
			flash.message = "You must be logged in to view seeds. Please log in or register."
			redirect(url:"/")
		}
	}
	
	/*
	 * This action finds a seed based on input params and directs to a page
	 * to display all information for that seed.
	 */
	def displaySeed =
	{
		Seed seed = Seed.get(params.id)
		if(seed)
			[seed:seed]
		else
		{
			flash.message = "Error displaying seed. Please try again."
			redirect(url:"/")
		}
	}
	
	/*
	 * This action handles the actual creation of a seed and adding it to the database 
	 * based on input parameters
	 */
	def createSeed =
	{
		def seed = new Seed()
		seed.hardiness = params.hardiness
		seed.harvesting = params.harvesting
		seed.commonName = params.commonName
		seed.scientificName = params.scientificName
		seed.seasonAvailable = params.seasonAvailable
		seed.tips = params.tips
		seed.specialRequirements = params.specialRequirements
		seed.farmerName = session.username
		seed.save()
		
		redirect(action: 'viewSeeds')
	
	}
}
